package com.kugoweb.shthon2011s.tlwatch.settings;

import twitter4j.TwitterException;
import twitter4j.auth.AccessToken;
import android.os.AsyncTask;

import com.kugoweb.shthon2011s.tlwatch.commons.SettingsData;
import com.kugoweb.shthon2011s.tlwatch.commons.TweetUtils;

public class SaveTokensTask extends AsyncTask<Void, Void, Void> {

	// private static final String TAG = SaveTokensTask.class.getSimpleName();

	public interface SaveTokensTaskListener {
		void onSaved(boolean deleted);
	}

	private final SettingsData mSettingsData;
	private final String mVerifier;
	private final SaveTokensTaskListener mListener;

	private boolean mDeleted;

	public SaveTokensTask(final SettingsData settingsData,
			final String verifier, final SaveTokensTaskListener listener) {
		this.mSettingsData = settingsData;
		this.mVerifier = verifier;
		this.mListener = listener;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.os.AsyncTask#doInBackground(Params[])
	 */
	@Override
	protected Void doInBackground(final Void... params) {
		try {
			String token;
			String secret;
			String screenName;
			if (mVerifier != null) {
				// 認証後
				final AccessToken at = TweetUtils.getAuth()
						.getOAuthAccessToken(mVerifier);
				token = at.getToken();
				secret = at.getTokenSecret();
				screenName = at.getScreenName();
				mDeleted = false;
			} else {
				// 認証情報削除
				token = "";
				secret = "";
				screenName = "";
				mDeleted = true;
			}

			mSettingsData.setTwitterToken(token);
			mSettingsData.setTwitterSecret(secret);
			mSettingsData.setTwitterScreenName(screenName);
		} catch (final TwitterException e) {
			// do nothing
			e.printStackTrace();
		}

		return null;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
	 */
	@Override
	protected void onPostExecute(final Void result) {
		mListener.onSaved(mDeleted);
	}

}
